package com.sptpc.learnspring.controller;

import com.sptpc.learnspring.global.response.BusinessStatusCode;
import com.sptpc.learnspring.global.response.GlobalResponse;
import com.sptpc.learnspring.model.User;
import com.sptpc.learnspring.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    // 注册
    @PostMapping("/register")
    public GlobalResponse register(@RequestBody User userRequest) {
        User user = new User();
        BeanUtils.copyProperties(userRequest, user);
        user.setPassword(
                passwordEncoder.encode(userRequest.getPassword())
        );
        user.setRole("ROLE_USER");
        if(userService.register(user)) {
            return GlobalResponse.success();
        } else {
            return GlobalResponse.fail(BusinessStatusCode.FAILURE);
        }
    }
}
